#include "mysql.h"


MYSQL *db_conn = NULL;



bool get_file_hash_from_db(const char *filename, char *file_hash) {
    char query[256];
    snprintf(query, sizeof(query), 
             "SELECT file_hash FROM files WHERE file_name='%s'", filename);

    if (mysql_query(db_conn, query)) {
        fprintf(stderr, "Query error: %s\n", mysql_error(db_conn));
        return false;
    }

    MYSQL_RES *result = mysql_store_result(db_conn);
    if (!result) {
        fprintf(stderr, "Store result error: %s\n", mysql_error(db_conn));
        return false;
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    if (!row) {
        fprintf(stderr, "File not found: %s\n", filename);
        mysql_free_result(result);
        return false;
    }

    // 复制哈希值到输出参数
    strncpy(file_hash, row[0], 64);
    file_hash[64] = '\0'; // 确保字符串终止

    mysql_free_result(result);
    return true;
}




bool db_check_hash(const char *hash) {
    char query[256];
    snprintf(query, sizeof(query), "SELECT 1 FROM files WHERE file_hash='%s'", hash);

    if (mysql_query(db_conn, query)) {
        fprintf(stderr, "Query error: %s\n", mysql_error(db_conn));
        return false;
    }

    MYSQL_RES *result = mysql_store_result(db_conn);
    bool exists = (mysql_num_rows(result) > 0);
    mysql_free_result(result);

    return exists;
}

bool db_insert_file(const char *name, const char *path, size_t size, const char *hash) {
    char query[512];
    snprintf(query, sizeof(query),
        "INSERT INTO files (file_name, file_path, file_size, file_hash) "
        "VALUES ('%s', '%s', %zu, '%s')",
        name, path, size, hash);

    if (mysql_query(db_conn, query)) {
        fprintf(stderr, "Insert error: %s\n", mysql_error(db_conn));
        return false;
    }

    printf("File record inserted: %s\n", name);
    return true;
}

void db_close() {
    if (db_conn) {
        mysql_close(db_conn);
        printf("MySQL connection closed.\n");
    }
}
